<template>
  <div>
    <div>
      <!-- check-strictly --- 在显示复选框的情况下，是否严格的遵循父子不互相关联的做法，默认为 false -->
      <!-- 为什么让父子不关联 -->
      <!-- 因为父级是菜单权限，二级按钮权限，用户可能只有菜单权限，没有按钮权限 -->
      <el-tree
        ref="tree"
        v-loading="loading"
        :data="permissionList"
        :props="{label:'name'}"
        default-expand-all
        show-checkbox
        check-strictly
        node-key="id"
        style="min-height:300px"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleId, assignPerm } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      permissionList: [], // 权限列表
      loading: false //  加载效果
    }
  },
  created() {
    this.getPermissionList()
    this.getRoleId()
  },
  methods: {
    // 获取所有的权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      // 转换数据为树形
      this.permissionList = tranListToTreeData(res.data)
    },

    // 获取已选的权限
    async getRoleId() {
      // 开启加载状态
      this.loading = true
      const res = await getRoleId(this.roleId)
      // console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
      // 关闭加载状态
      this.loading = false
    },

    // 取消分配权限
    cancelButton() {
      // 取消分配权限，让父级关闭弹框
      this.$emit('close')
    },
    // 分配权限
    async setRolesBtn() {
    // 拿到选择的权限
      const permIds = this.$refs.tree.getCheckedKeys()
      // 调用 API 发请求
      const res = await assignPerm({ id: this.roleId, permIds })
      // 提示用户
      this.$message.success(res.message)
      // 分配权限成功，让父级关闭弹框
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
